package com.huawei.esdk.tpoa.tools.cxf.utils;

import java.util.Map;
import org.apache.log4j.Logger;
import com.google.gson.Gson;
import com.huawei.esdk.tpoa.tools.action.CreateScript;

public class LoggerMgr
{
    private static Gson gson = new Gson();
    
    private static final Logger LOGGER = Logger
        .getLogger(LoggerMgr.class);
    
    private static String[] SENSITIVE_WORDS;

    static 
    {
        SENSITIVE_WORDS = getSensitiveWords();
    }
    /**
     *调用时间、操作类型、调用接口名称、
     *详细的接口参数、客户端IP、
     *调用者的用户标识、成功或失败标识
     */
    public static void interfacelogger(InterfaceOperationType operationType,
        String interfaceName,
        Object msg, Integer errCode)
    {
        StringBuffer sb = new StringBuffer();
        sb.append(operationType.toString()).append(" | ");
        sb.append(interfaceName).append(" | ");
        
        String msgStr = gson.toJson(msg);
        msgStr = hideSensitiveWords(msgStr,SENSITIVE_WORDS);
        sb.append(msgStr).append(" | ");

        
        Map<String, String> map = System.getenv();
        String computeruserName = map.get("USERNAME");
        sb.append(computeruserName).append(" | ");
        
        String userName = CreateScript.userName;
        sb.append(userName).append(" | ");
        
        String status = 0 == errCode ? errCode+" successfully" :
            errCode+" failed";
        sb.append(status).append(" | ");
        
        LOGGER.info(sb.toString());
    }

    private static String hideSensitiveWords(String msgStr, 
        String[] sensitiveWords)
    {
        for(String str : sensitiveWords)
        {
            String indexStr = str + "\":\"";
            int index = msgStr.indexOf(indexStr);
            if(-1 != index)
            {
                String s1 = msgStr.substring(0, index+indexStr.length());
                String s2 = msgStr.substring(index+indexStr.length());
                s2 = "******" + s2.substring(s2.indexOf("\""));
                msgStr = s1 + s2;
            }
        }
        return msgStr;
    }
    
    private static String[] getSensitiveWords()
    {
        String proper = "password,chairmanPassword,encryptPassword";
        return null == proper ? new String[0] : proper.split(",");
    }
}